<template>
  <view
    class="m-t20 bg-1 r-20 relative expansion-panel overflow-hidden"
    :style="[{ maxHeight: `${panelHeight}px` }]">
    <view :id="contentId" class="expansion-panel__body">
      <slot></slot>
    </view>
    <view v-if="expandable" class="flex-c fold" @click="toggle">
      <image
        v-if="!expanded"
        class="fold-icon"
        src="@/static/images/office/chevron-down.png"
        mode="aspectFit" />
      <image
        v-else
        class="fold-icon"
        src="@/static/images/office/chevron-up.png"
        mode="aspectFit" />
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { defineExpose, getCurrentInstance, nextTick, onMounted, ref } from 'vue'
  import { genRandomId, getNodeRect } from '@/utils/utils'

  const vm = getCurrentInstance()

  const contentId = genRandomId('expansionPanelBody')

  const fixedHeight = uni.upx2px(780)
  let contentHeight = 0

  const panelHeight = ref(fixedHeight)
  const expandable = ref(false)
  const expanded = ref(false)

  const toggle = () => {
    if (!expandable.value) return

    panelHeight.value = expanded.value ? fixedHeight : contentHeight
    expanded.value = !expanded.value
  }

  const getDomRect = () => {
    getNodeRect(`#${contentId}`, vm).then((rect) => {
      contentHeight = rect.height!
      expandable.value = contentHeight > fixedHeight
    })
  }

  const refresh = () => {
    nextTick(getDomRect)
  }

  defineExpose({ refresh })

  onMounted(() => {
    refresh()
  })
</script>

<style lang="scss" scoped>
	.expansion-panel {
		max-height: 780rpx;
		transition-duration: 300ms;
		transition-property: max-height;
	}
	.fold {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		height: 80rpx;
		background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 80%);
		&-icon {
			width: 32rpx;
			height: 19rpx;
		}
	}
</style>
